/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jili.ubert.clientapi;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;

/**
 *
 * @author ChengJiLi
 */
class MsgDecoder extends LengthFieldBasedFrameDecoder {

    /**
     * @param byteOrder
     * @param maxFrameLength 字节最大长度,大于此长度则抛出异常
     * @param lengthFieldOffset 开始计算长度位置,这里使用0代表放置到最开始
     * @param lengthFieldLength 描述长度所用字节数
     * @param lengthAdjustment 长度补偿,这里由于命令码使用4个字节.需要将原来长度计算加4
     * @param initialBytesToStrip 开始计算长度需要跳过的字节数
     * @param failFast
     */
    public MsgDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(byteOrder, maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    public MsgDecoder() {
        this(ByteOrder.BIG_ENDIAN, 100000, 0, 4, 8, 4, true);
    }

    /**
     * 根据构造方法自动处理粘包,半包.然后调用此decode
     *
     */
    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {

        ByteBuf frame = (ByteBuf) super.decode(ctx, byteBuf);
        if (frame == null) {
            return null;
        }

        int cmd = frame.readInt();// 先读取两个字节命令码
        int sessionID = frame.readInt();// 再读4个字节的对话ID

        byte[] data = new byte[frame.readableBytes()];// 其它数据为实际数据
        frame.readBytes(data);
        MsgEntity msgVO = new MsgEntity();
        System.out.println("Decode收到数据" + ctx.channel());
        msgVO.setChannel(ctx.channel());
        msgVO.setCmdCode(cmd);
        msgVO.setSessionID(sessionID);
        data[0] = (byte) (data[0] - 1);
        msgVO.setData(data);
        return msgVO;
    }

}
